import m from "../models/User";
import utils from "../utils";
import mEmailCode from "../models/EmailCode";
import mPhoneCode from "../models/PhoneCode";
import mUser from "../models/User";

const _ = require("lodash");

import { model } from "../models/User";

import * as config from "../config";

import { Request, Response } from "express";
import { NextFunction } from "express-serve-static-core";

import { IResponse, IVerify } from "../types/index";
import * as cSliderCode from "./sliderCode";

export interface IUser {}

export async function login(req: Request, res: Response, next: NextFunction) {
  const { code, password, username, verify } = req.body;
  const user = await m.findByUsername(username);
  let modelUser: any = undefined;
  if (!!user) {
    modelUser = utils.getDataByModel(user, model);
  }
  const form: any = {
    username: {
      valid: true,
      has: {
        valid: true
      }
    },
    password: {
      valid: true,
      // 密码是否匹配
      eq: {
        valid: true
      }
    },
    code: {
      valid: true,
      // 密码是否匹配
      eq: {
        valid: true
      }
    },
    verify: {
      valid: true,
      eq: {
        valid: true
      }
    },
    valid: false
  };
  const validateForm = async () => {
    // 用户是否存在
    form.username.has.valid = !!user;

    // 密码是否匹配
    if (!!modelUser) {
      form.password.eq.valid = modelUser.password === password;
    }

    // 短信或手机是否匹配
    form.code.eq.valid = await validateCode(code, username);

    //图形验证码是否匹配

    form.verify.eq.valid = await cSliderCode.validateVerify(verify);

    let valid = true;

    _.forEach(form, (item: any, key: string) => {
      if (item && item.hasOwnProperty("valid")) {
        let itemValid = true;
        _.forEach(item, (it: any, k: string) => {
          if (it && it.hasOwnProperty("valid")) {
            valid = valid && it.valid;
            itemValid = itemValid && it.valid;
          }
        });
        form[key].valid = itemValid;
      }
    });

    form.valid = valid;

    return form;
  };

  await validateForm();

  if (form.valid) {
    res.locals.data = {
      data: modelUser
    };
    res.cookie("uid", "ffffffff");
    // return next();
    res.json({
      code: 200,
      data: undefined,
      msg: "success"
    });
    return;
  }
  if (!form.username.has.valid) {
    res.locals.data = {
      msg: "用户名不存在",
      data: undefined,
      code: "user_no_username"
    };

    return next();
  }
  if (!form.password.eq.valid) {
    res.locals.data = {
      msg: "密码不正确",
      data: undefined,
      code: "user_neq_password"
    };
    return next();
  }
  if (!form.code.eq.valid) {
    res.locals.data = {
      msg: "验证码不正确",
      data: undefined,
      code: "user_neq_code"
    };
    return next();
  }
  next();
}

export async function enroll(req: Request, res: Response, next: NextFunction) {
  const { code, password, username, verify } = req.body;
  const user = await m.findByUsername(username);
  let modelUser: any = undefined;
  if (!!user) {
    modelUser = utils.getDataByModel(user, model);
  }
  const form: any = {
    username: {
      valid: true,
      // 用户名不存在
      none: {
        valid: true
      }
    },
    // password: {
    //   valid: true,
    //   // 密码是否匹配
    //   eq: {
    //     valid: true,
    //   },
    // },
    code: {
      valid: true,
      // 密码是否匹配
      eq: {
        valid: true
      }
    },
    verify: {
      valid: true,
      // 密码是否匹配
      eq: {
        valid: true
      }
    },
    valid: false
  };
  const validateForm = async () => {
    // 用户是否不存在
    form.username.none.valid = !user;

    // 验证码是否匹配
    form.code.eq.valid = await validateCode(code, username);

    //图形验证码是否匹配

    form.verify.eq.valid = await cSliderCode.validateVerify(verify);

    let valid = true;

    _.forEach(form, (item: any, key: string) => {
      if (item && item.hasOwnProperty("valid")) {
        let itemValid = true;
        _.forEach(item, (it: any, k: string) => {
          if (it && it.hasOwnProperty("valid")) {
            valid = valid && it.valid;
            itemValid = itemValid && it.valid;
          }
        });
        form[key].valid = itemValid;
      }
    });

    form.valid = valid;

    return form;
  };

  await validateForm();

  if (form.valid) {
    res.locals.data = {
      data: undefined
    };
    try {
      await mUser.create({ ...utils.formatUsername(username), password });
    } catch (e) {
      console.log(e);
      res.locals.data = {
        code: 7001,
        data: undefined,
        msg: "do error"
      };
      return next();
    }
    return next();
  }

  if (!form.verify.eq.valid) {
    res.locals.data = {
      msg: "图形验证码不正确",
      data: undefined,
      code: "user_neq_verify"
    };
    return next();
  }
  if (!form.username.none.valid) {
    res.locals.data = {
      msg: "用户名已存在",
      data: undefined,
      code: "user_username_has_exsits"
    };
    return next();
  }

  if (!form.code.eq.valid) {
    res.locals.data = {
      msg: "验证码不正确",
      data: undefined,
      code: "user_neq_code"
    };
    return next();
  }

  next();
}

export async function validateCode(code: string, username: string) {
  if (utils.isEmail(username)) {
    return await mEmailCode.validateEmailCode(code, username);
  }
  if (utils.isPhone(username)) {
    return await mPhoneCode.validatePhoneCode(code, username);
  }
  return false;
}
